import { Cascader, Form, Input, message, Modal, Select, type FormProps } from "antd";
import { useEffect, useState, useRef } from "react";
import { buildingList } from "../../apis/building";
import type { addHouseParams, editFace } from "../../type/house";
import { transformBuildingData2 } from "../../utils/tree2";
import { addHouse } from "../../apis/house";
import { findBuildingPath } from "../../utils/findBuildingPath";

interface PropsParams {
    openAdd: boolean;
    refresh: () => void;
    editContent: editFace|null
}

type FieldType = {
    id?: number;
    buildingid: number;
    houseno: string;
    areas: number;
    type: string;
    orientation: string
};

interface Option {
    value: string;
    label: string;
    children?: Option[];
}
interface TypeFace {
    one: string;
    two: string
}
function AddDiaLog({ openAdd, refresh, editContent }: PropsParams) {
    const [isModalOpen, setIsModalOpen] = useState(openAdd);
    const formRef = useRef<any>(null); // 创建表单引用
    // 楼栋选择框的填充
    const [BuildingData, setBuildingData] = useState<Option[]>()
    // 房型选择框的填充
    const [orientationArray] = useState<string[]>(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']);
    // 朝向选择框的填充
    const [orientationArray2] = useState<string[]>(['朝北', '朝南', '朝西', '朝东', '东北', '东南', '西北', '西南']);

    const [typeArray, setTypeArray] = useState<TypeFace>({ one: '', two: '' })
    useEffect(() => {
        getBuilding()
    }, []);
    const getBuilding = async () => {
        let res = await buildingList()
        setBuildingData(transformBuildingData2(res.data.list))
    }
    useEffect(() => {
        if (!isModalOpen) {
            // 当模态框关闭时，通知父组件更新状态
            // 这样可以确保下次打开时状态是同步的
            setTypeArray({one:'',two:''})
            refresh();
        }
    }, [isModalOpen]);
    useEffect(() => {
        if (editContent?.id && formRef.current) {
            // 房屋类型回显
            if (editContent.data?.type && formRef.current) {
                const typeValue = editContent.data.type;
                if (typeValue.length >= 4) {
                    setTypeArray({
                        one: typeValue.substring(0, 2),
                        two: typeValue.substring(2, 4)
                    });
                }
            }
            // 楼栋回显
            let buildingPath: string[] | undefined;
            if (editContent?.data?.buildingid && BuildingData) {
                buildingPath = findBuildingPath(editContent.data.buildingid, BuildingData);
            }
            // 整个表单进行回显
            formRef.current.setFieldsValue({
                buildingid: buildingPath,
                houseno: editContent?.data?.houseno,
                areas: editContent?.data?.areas,
                type: editContent?.data?.type,
                orientation: editContent?.data?.orientation
            });

        } else if (formRef.current) {
            formRef.current.resetFields(); // 清空表单
        }
    }, [editContent]);

    useEffect(() => {
        setIsModalOpen(openAdd);
    }, [openAdd]);

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        editContent?.id ? edit(values) : Add(values)
    };
    const edit = async (values: FieldType) => {
        // 处理楼栋ID，如果它是数组则取最后一个值
        const processedValues = { ...values };

        // 如果buildingid是数组（来自Cascader），取最后一个值
        if (Array.isArray(values.buildingid)) {
            const buildingArray = values.buildingid as unknown as (string | number)[];
            if (buildingArray.length > 0) {
                processedValues.buildingid = Number(buildingArray[buildingArray.length - 1]);
            }
        }
        processedValues.id = editContent?.id
        let res = await addHouse(processedValues as addHouseParams)
        if (res.errCode == 10000) {
            message.success('修改成功');
            refresh()
            formRef.current?.resetFields(); // 清空表单数据
        } else {
            message.error('修改失败');
        }
        setIsModalOpen(false);
    };
    const Add = async (values: FieldType) => {
        // 处理楼栋ID，如果它是数组则取最后一个值
        const processedValues = { ...values };

        // 如果buildingid是数组（来自Cascader），取最后一个值
        if (Array.isArray(values.buildingid)) {
            const buildingArray = values.buildingid as unknown as (string | number)[];
            if (buildingArray.length > 0) {
                processedValues.buildingid = Number(buildingArray[buildingArray.length - 1]);
            }
        }

        processedValues.id = 0
        let res = await addHouse(processedValues as addHouseParams)
        if (res.errCode == 10000) {

            message.success('添加成功');
            refresh()
            formRef.current?.resetFields(); // 清空表单数据
        } else {
            message.error('添加失败');
        }
        setIsModalOpen(false);
    }

    const handleOk = () => {
        formRef.current?.submit(); // 触发表单提交
    };
    // 监听 typeArray 发送变化后修改 from 表单字段 type的值
    useEffect(() => {
        if (formRef.current) {
            const typeValue = typeArray.one && typeArray.two ? typeArray.one + typeArray.two : undefined;
            formRef.current.setFieldsValue({ type: typeValue });
        }
    }, [typeArray]);
    return (
        <Modal
            title={editContent?.id ? '修改房间' : '添加房间'}
            closable={{ 'aria-label': 'Custom Close Button' }}
            open={isModalOpen}
            onOk={handleOk}  // 使用 handleOk 替代 onFinish
            onCancel={handleCancel}
            okText="确认"
            cancelText="取消"
        >
            <Form
                ref={formRef}  // 绑定表单引用
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 600 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="楼栋"
                    name="buildingid"
                    rules={[{ required: true, message: '请选择楼栋' }]}
                >
                    <Cascader options={BuildingData} placeholder="选择楼栋" />
                </Form.Item>
                <Form.Item<FieldType>
                    label="房间号"
                    name="houseno"
                    rules={[{ required: true, message: '请输入房间号' }]}
                >
                    <Input placeholder="请输入房间号" />
                </Form.Item>
                <Form.Item<FieldType>
                    label="房屋面积"
                    name="areas"
                >
                    <Input placeholder="请输入面积" />
                </Form.Item>
                <Form.Item<FieldType>
                    label="房屋类型"
                    name='type'
                >
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Select
                            style={{ width: '160px' }}
                            showSearch
                            value={typeArray.one || undefined}
                            optionFilterProp="label"
                            allowClear
                            onChange={(value: string) => {
                                setTypeArray({ ...typeArray, one: value })
                            }}
                            options={orientationArray.map((item: string) => {
                                return { value: item + '室', label: item + '室' }
                            })}
                        />
                        <Select
                            style={{ width: "120px" }}
                            showSearch
                            optionFilterProp="label"
                            value={typeArray.two || undefined}
                            allowClear
                            onChange={(value: string) => {
                                setTypeArray({ ...typeArray, two: value })
                            }}
                            options={orientationArray.map((item: string) => {
                                return { value: item + '厅', label: item + '厅' }
                            })}
                        />
                    </div>
                </Form.Item>
                <Form.Item<FieldType>
                    label="房屋朝向"
                    name='orientation'
                >
                    <Select
                        showSearch
                        placeholder="选择朝向"
                        optionFilterProp="label"
                        allowClear
                        options={orientationArray2.map((item: string) => {
                            return { value: item, label: item }
                        })}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
}
export default AddDiaLog